﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;

namespace WindowsFormsApplication1
{
    public class SerialPortCommunicator
    {
        private readonly SerialPort _serialPort;
        private readonly object _lock = new object();
        private readonly Queue<byte[]> _sendQueue = new Queue<byte[]>();
        private readonly CancellationTokenSource _cancellationTokenSource;
        private const int SendInterval = 100; // 发送间隔为100毫秒
        private bool _isSending;

        public SerialPortCommunicator()
        {
            _serialPort = new SerialPort
            {
                PortName = "COM7",
                BaudRate = 9600,
                Parity = Parity.Even,
                DataBits = 8,
                StopBits = StopBits.One
            };

            _serialPort.DataReceived += SerialPort_DataReceived;
            _cancellationTokenSource = new CancellationTokenSource();
            StartSendTask();
        }

        public void Start()
        {
            lock (_lock)
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                    Console.WriteLine("串口已打开并常驻后台");
                }
            }
        }

        public void Stop()
        {
            lock (_lock)
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Close();
                    Console.WriteLine("串口已关闭");
                }
            }
            _cancellationTokenSource.Cancel();
        }

        // 发送数据 (将数据添加到队列)
        public void SendData(byte[] data)
        {
            lock (_sendQueue)
            {
                _sendQueue.Enqueue(AppendCRC(data));
            }
        }

        // 定时器后台任务，用于间隔发送队列中的数据
        private void StartSendTask()
        {
            Task.Run(async () =>
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    if (_isSending)
                    {
                        await Task.Delay(SendInterval); // 控制发送频率
                        continue;
                    }

                    byte[] dataToSend = null;

                    lock (_sendQueue)
                    {
                        if (_sendQueue.Count > 0)
                        {
                            dataToSend = _sendQueue.Dequeue();
                            _isSending = true;
                        }
                    }

                    if (dataToSend != null)
                    {
                        SendToPort(dataToSend);
                        await Task.Delay(SendInterval); // 发送完成后再延时
                    }

                    _isSending = false;
                }
            }, _cancellationTokenSource.Token);
        }

        // 直接发送数据到串口
        private void SendToPort(byte[] data)
        {
            lock (_lock)
            {
                if (_serialPort.IsOpen)
                {
                    _serialPort.Write(data, 0, data.Length);
                    Console.WriteLine($"发送数据 (Hex): {BitConverter.ToString(data).Replace("-", " ")}");
                }
                else
                {
                    Console.WriteLine("串口未打开，无法发送数据");
                }
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            lock (_lock)
            {
                try
                {
                    int bytesToRead = _serialPort.BytesToRead;
                    byte[] receivedBuffer = new byte[bytesToRead];
                    _serialPort.Read(receivedBuffer, 0, bytesToRead);
                    Console.WriteLine($"接收数据 (Hex): {BitConverter.ToString(receivedBuffer).Replace("-", " ")}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"接收数据出错: {ex.Message}");
                }
            }
        }

        // 计算并附加CRC16校验
        private byte[] AppendCRC(byte[] data)
        {
            ushort crc = CalculateCRC16(data);
            byte[] dataWithCRC = new byte[data.Length + 2];
            Array.Copy(data, dataWithCRC, data.Length);
            dataWithCRC[data.Length] = (byte)(crc & 0xFF);        // CRC低位
            dataWithCRC[data.Length + 1] = (byte)((crc >> 8) & 0xFF); // CRC高位
            return dataWithCRC;
        }

        // CRC16计算方法
        private ushort CalculateCRC16(byte[] data)
        {
            ushort crc = 0xFFFF;
            for (int i = 0; i < data.Length; i++)
            {
                crc ^= data[i];
                for (int j = 0; j < 8; j++)
                {
                    if ((crc & 0x0001) != 0)
                    {
                        crc >>= 1;
                        crc ^= 0xA001;
                    }
                    else
                    {
                        crc >>= 1;
                    }
                }
            }
            return crc;
        }
    }
}
